package com.ytjj.qmyx.admin.service.impl;

import com.github.pagehelper.PageHelper;
import com.ytjj.common.api.CommonPage;
import com.ytjj.common.constants.CopyWriterConstant;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.utils.CopyWriterConfigUtil;
import com.ytjj.qmyx.admin.constants.SysConfigConstants;
import com.ytjj.qmyx.admin.dao.*;
import com.ytjj.qmyx.admin.model.ProductSpecialAddRequest;
import com.ytjj.qmyx.admin.model.request.DynamicSpecialRequest;
import com.ytjj.qmyx.admin.model.request.SpecialProListRequest;
import com.ytjj.qmyx.admin.model.request.SpecialRecomListRequest;
import com.ytjj.qmyx.admin.model.request.SpecialRequest;
import com.ytjj.qmyx.admin.model.response.*;
import com.ytjj.qmyx.admin.service.ProductCategoryService;
import com.ytjj.qmyx.admin.service.SpecialService;
import com.ytjj.qmyx.mall.mapper.*;
import com.ytjj.qmyx.mall.model.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class SpecialServiceImpl implements SpecialService {

    @Resource
    private SpecialDao specialDao;

    @Resource
    private ProductSpecialDao productSpecialDao;

    @Resource
    private SpecialMapper specialMapper;

    @Resource
    private ProductSpecialMapper productSpecialMapper;

    @Resource
    private DynamicDao dynamicDao;

    @Resource
    private DynamicMapper dynamicMapper;

    @Resource
    private DynamicSpecialMapper dynamicSpecialMapper;

    @Resource
    private DynamicSpecialDao dynamicSpecialDao;

    @Resource
    private ProductMapper productMapper;

    @Resource
    private ProductDao productDao;

    @Resource
    private BankerMapper bankerMapper;

    @Resource
    private CopyWriterConfigUtil copyWriterConfigUtil;

    @Resource
    private ProductCategoryDao productCategoryDao;

    @Resource
    private ProductCategoryService productCategoryService;

    @Override
    public CommonPage<SpecialResp> list(SpecialRequest specialRequest) {
        PageHelper.startPage(specialRequest.getPageNum(), specialRequest.getPageSize());
        List<SpecialResp> specials = specialDao.selectSpecialList(specialRequest);
        for (SpecialResp special : specials) {
            //获取分类id
            String categoryListStr = special.getCategoryListStr();
            if (StringUtils.isEmpty(categoryListStr)) {
                continue;
            }
            String[] split = categoryListStr.split(",");
            List<Integer> ids = new ArrayList<>();
            for (String s : split) {
                ids.add(Integer.valueOf(s));
            }
            //通过所得的ids获取到分类对象集合
            List<ProductCategoryResp> list = productCategoryDao.selectCategoryByIds(ids);
            //分类集合进行排序(三级放二级,二级放一级里)
            List<ProductCategoryResp> productCategoryResp = productCategoryService.getProductCategoryResps(list);
            //定义好一二三级分类
            List<String> topCategoryList = new ArrayList<>();//一级分类
            if (1 == special.getCategoryType()) {
                special.setOneCategoryIds(ids);
                list.forEach(item -> {
                    topCategoryList.add(item.getTitle());
                });
                special.setTopCategoryList(topCategoryList);//一级分类
            } else {
                List<String> twoCategoryList = new ArrayList<>();//二级分类
                List<String> bottomCategoryList = new ArrayList<>();//三级分类
                List<List<Integer>> categoryList = new ArrayList<>();//分类集合
                productCategoryResp.forEach(category -> {
                    topCategoryList.add(category.getTitle());
                    List<ProductCategoryResp> childProductCategory = category.getChildProductCategory();
                    if (!CollectionUtils.isEmpty(childProductCategory)) {
                        childProductCategory.forEach(twoCategory -> {
                            twoCategoryList.add(twoCategory.getTitle());
                            List<ProductCategoryResp> bottomProductCategory = twoCategory.getChildProductCategory();
                            if (!CollectionUtils.isEmpty(bottomProductCategory)) {
                                bottomProductCategory.forEach(bottomCategory -> {
                                    bottomCategoryList.add(bottomCategory.getTitle());
                                    List<Integer> categoryIds = new ArrayList<>();
                                    categoryIds.add(category.getId());
                                    categoryIds.add(twoCategory.getId());
                                    categoryIds.add(bottomCategory.getId());
                                    categoryList.add(categoryIds);
                                });
                            } else {
                                List<Integer> categoryIds = new ArrayList<>();
                                categoryIds.add(category.getId());
                                categoryIds.add(twoCategory.getId());
                                categoryList.add(categoryIds);
                            }
                        });
                    } else {
                        List<Integer> categoryIds = new ArrayList<>();
                        categoryIds.add(category.getId());
                        categoryList.add(categoryIds);
                    }
                });
                special.setTopCategoryList(topCategoryList);//一级分类
                special.setTwoCategoryList(twoCategoryList);//二级分类
                special.setBottomCategoryList(bottomCategoryList);//三级分类
                special.setCategoryList(categoryList);//分类id集合
            }
        }
        return CommonPage.restPage(specials);
    }


    @Override
    public int create(Special special) {
        special.setCreateTime(new Date());
        special.setStatus((byte) 0);
        return specialMapper.insert(special);
    }

    @Override
    public int update(Special special) {
        special.setUpdateTime(new Date());
        return specialMapper.updateByPrimaryKey(special);
    }

    @Override
    public Special getSpecialById(Integer id) {
        return specialMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateStatus(Integer id) {
        Special special = specialMapper.selectByPrimaryKey(id);
        if (special.getStatus() == 1) {
            special.setStatus((byte) 0);
        } else if (special.getStatus() == 0) {
            special.setStatus((byte) 1);
        }
        special.setUpdateTime(new Date());
        return specialMapper.updateByPrimaryKeySelective(special);
    }

    @Override
    public CommonPage<SpecialProductResponse> getProductListById(SpecialProListRequest specialProListRequest) {
        PageHelper.startPage(specialProListRequest.getPageNum(), specialProListRequest.getPageSize());
        List<SpecialProductResponse> products = specialDao.getProductListById(specialProListRequest);
        return CommonPage.restPage(products);
    }

    @Override
    public int isRecommendFlag(Integer productId, Integer specialId, Integer recommendFlag) {
        return productSpecialDao.isRecommendFlag(productId, specialId, recommendFlag);
    }

    @Override
    public List<Special> getSpecialList() {
        List<Special> specialList = specialDao.getSpecialList();
        for (Special special : specialList) {
            if ("mall".equals(special.getType())){
                special.setTitle(special.getTitle() + "-1");
            }
        }
        return specialList;
    }

    @Override
    public List<SpecialResponse> getDynamicSpecialList() {
        return specialDao.getDynamicSpecialList();
    }

    /**
     * 删除专区(逻辑删除)
     * @param id
     * @return
     */
    @Override
    public int deleteSpecial(Integer id) {
        return specialDao.updateSpecial(id);
    }

    @Override
    public List<DynamicCategoryResponse> getDynamicCategory() {
        List<DynamicCategoryResponse> responses = specialDao.getDynamicCategory();
        return responses;
    }

    @Override
    public CommonPage<SpecialRecommendResponse> getRecommendListById(SpecialRecomListRequest specialRecomListRequest) {
        PageHelper.startPage(specialRecomListRequest.getPageNum(), specialRecomListRequest.getPageSize());
        List<SpecialRecommendResponse> products = specialDao.getRecommendListById(specialRecomListRequest);
        if (!CollectionUtils.isEmpty(products)) {
            for (SpecialRecommendResponse specialRecommendResponse : products) {
                Banker banker = bankerMapper.selectByPrimaryKey(specialRecommendResponse.getBankerId());
                specialRecommendResponse.setBankerName(banker.getName());
            }
        }
        return CommonPage.restPage(products);
    }

    @Override
    public List<Product> getProducts(Integer bankerId) {
        ProductExample productExample = new ProductExample();
        productExample.createCriteria().andBankerIdEqualTo(bankerId);
        return productMapper.selectByExample(new ProductExample());
    }

    @Override
    public int addProductSpecial(ProductSpecialAddRequest productSpecialAdd) {
        // 校验该商品是否存在
        Integer num = productDao.checkedProductAdd(productSpecialAdd.getProductId(), productSpecialAdd.getSpecialType());
        if (num == 0) {
            throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.COMMODITY_NOT_EXIST));
        }

        ProductSpecial productSpecial = new ProductSpecial();
        BeanUtils.copyProperties(productSpecialAdd, productSpecial);
        Integer exist = productSpecialDao.checkSpecialProduct(productSpecial);
        if (exist > 0) {
            throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.PREFECTURE_EXIST));
        }
        productSpecial.setCreateTime(new Date());
        productSpecial.setStatus((byte) 2);              // 默认下架
        return productSpecialMapper.insertSelective(productSpecial);
    }

    @Override
    public int updateProductSpecial(ProductSpecial productSpecial) {
        productSpecial.setUpdateTime(new Date());
        return productSpecialDao.updateProductSpecial(productSpecial);
    }

    @Override
    public int updateProductSpecialStatus(Integer specialId, Integer productId) {
        List<ProductSpecial> productSpecials = productSpecialDao.selectProductSpecial(specialId, productId);
        ProductSpecial productSpecial = productSpecials.get(0);
        if (productSpecial.getStatus() == SysConfigConstants.Product_Status.STATUS_1) {
            productSpecial.setStatus(SysConfigConstants.Product_Status.STATUS_2);
        } else if (productSpecial.getStatus() == SysConfigConstants.Product_Status.STATUS_2) {
            productSpecial.setStatus(SysConfigConstants.Product_Status.STATUS_1);
        }
        productSpecial.setUpdateTime(new Date());
        return productSpecialMapper.updateByPrimaryKeySelective(productSpecial);
    }

    @Override
    public int deleteProductSpecial(Integer specialId, Integer productId) {
        return productSpecialDao.deleteProductSpecial(specialId, productId);
    }

    @Override
    public CommonPage<DynamicModeResponse> getDynamicsById(DynamicSpecialRequest dynamicSpecialRequest) {
        PageHelper.startPage(dynamicSpecialRequest.getPageNum(), dynamicSpecialRequest.getPageSize());
        List<DynamicModeResponse> dynamics = dynamicDao.getDynamicsById(dynamicSpecialRequest);
        return CommonPage.restPage(dynamics);
    }

    @Override
    public List<Dynamic> getDynamics() {
        return dynamicMapper.selectByExample(new DynamicExample());
    }

    @Override
    public int addDynamicSpecial(DynamicSpecial dynamicSpecial) {

        // 效验动态id是否存在
        int count = dynamicDao.selectCount(dynamicSpecial.getDynamicId());
        if (count == 0) {
            throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.DYNAMIC_ID_NOT_EXIST));
        }

        // 效验是否已经存在该动态
        int isExists = dynamicDao.isExists(dynamicSpecial.getSpecialId(), dynamicSpecial.getDynamicId());
        if (isExists > 0) {
            throw new ApiException("该动态已存在，请勿重复添加！");
        }

        dynamicSpecial.setCreateTime(new Date());
        // 默认上架
        dynamicSpecial.setStatus(1);
        return dynamicSpecialMapper.insert(dynamicSpecial);
    }

    @Override
    public int updateDynamicSpecial(DynamicSpecial dynamicSpecial) {
        dynamicSpecial.setUpdateTime(new Date());
        return dynamicSpecialDao.updateDynamicSpecial(dynamicSpecial);
    }

    @Override
    public int updateDynamicSpecialStatus(Integer specialId, Integer dynamicId) {
        DynamicSpecial dynamicSpecial = dynamicSpecialDao.selectDynamicSpecial(specialId, dynamicId);
        if (dynamicSpecial.getStatus() == 1) {
            dynamicSpecial.setStatus(2);
        } else if (dynamicSpecial.getStatus() == 2) {
            dynamicSpecial.setStatus(1);
        }
        dynamicSpecial.setUpdateTime(new Date());
        return dynamicSpecialMapper.updateByPrimaryKeySelective(dynamicSpecial);
    }

    @Override
    public int deleteDynamicSpecial(Integer specialId, Integer dynamicId) {
        return dynamicSpecialDao.deleteDynamicSpecial(specialId, dynamicId);
    }


}
